//
//  MYSimpleWebVC.m
//  JQLive
//
//  Created by Bruce on 2020/1/14.
//  Copyright © 2020 JQLive. All rights reserved.
//

#import "MYSimpleWebVC.h"
#import <WebKit/WebKit.h>

@interface MYSimpleWebVC ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler,UINavigationControllerDelegate>
{
    BOOL isHiddenBackButton;
}
@property (nonatomic,strong) NSURL *url;
@property (nonatomic,strong) WKWebView *webView;
@property (nonatomic, strong) UIProgressView *myProgressView;
@end

@implementation MYSimpleWebVC

- (UIProgressView *)myProgressView
{
    if (!_myProgressView)
    {
        _myProgressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, self.topControlHeight, SCREEN_WIDTH, 0)];
        _myProgressView.tintColor = [UIColor blackColor];
        _myProgressView.trackTintColor = [UIColor clearColor];
    }
    
    return _myProgressView;
}

- (WKWebView *)webView
{
    if(!_webView)
    {
        _webView = [[WKWebView alloc] init];
        _webView.backgroundColor = [UIColor whiteColor];
        _webView.scrollView.showsVerticalScrollIndicator = NO;
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
    }
    return _webView;
}

- (instancetype)initWithURLString:(NSString *)urlString
{
    if(self = [super init])
    {
        self.urlString = urlString;
        self.url = [NSURL URLWithString:urlString];
    }
    return self;
}

- (instancetype)initWithURLString:(NSString *)urlString withTitle:(NSString *)title
{
    if(self = [super init])
    {
        self.urlString = urlString;

        self.title = title;
        self.url = [NSURL URLWithString:urlString];
    }
    return self;
}

- (instancetype)initWithURLString:(NSString *)urlString isHiddenBackButton:(BOOL)isHidden
{
    if(self = [super init])
    {
        self.urlString = urlString;
        self.url = [NSURL URLWithString:urlString];
        isHiddenBackButton = isHidden;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if(self.urlString)
    {
        self.url = [NSURL URLWithString:self.urlString];
    }
    DLog(@"HTML地址：%@",self.urlString);
    [self layout];
}
// 系统状态栏
- (UIStatusBarStyle)preferredStatusBarStyle{
//    return UIStatusBarStyleLightContent;
    return UIStatusBarStyleDefault;
}
#pragma mark - Intial Methods
- (void)setupNavigationItems
{
    [super setupNavigationItems];

    if (isHiddenBackButton)
    {
        BaseUINavigationButton *leftButton = [[BaseUINavigationButton alloc] initWithType:QMUINavigationButtonTypeImage];
        leftButton.frame = CGRectMake(0, 0, (44), (44));
        [leftButton setTitle:@"" forState:0];
        leftButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
        UIBarButtonItem * leftItem = [UIBarButtonItem qmui_itemWithButton:leftButton target:self action:nil];
        self.navigationItem.leftBarButtonItems = @[leftItem];
    }
}

- (void)layout
{
    [self.view addSubview:self.webView];
    
    if (isHiddenBackButton)
    {
        [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(@(-self.topControlHeight+self.statusBarHeight));
            make.left.right.bottom.equalTo(self.view);
        }];
    }
    else
    {
        [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(@(self.topControlHeight));
            make.left.right.bottom.equalTo(self.view);
        }];
    }
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:self.url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:20.0];
    
    [self.webView loadRequest:request];
}

///// 设置导航栏的背景图，默认为 NavBarBackgroundImage
- (nullable UIImage *)navigationBarBackgroundImage
{
    if (isHiddenBackButton)
    {
        return [UIImage new];
    }
    else
    {
        return [UIImage imageWithColor:[UIColor whiteColor] size:CGSizeMake(SCREEN_WIDTH, self.topControlHeight)];
    }
}

- (void)dealloc
{
    if(self.webView.loading)
    {
        [self.webView stopLoading];
        [self.webView removeFromSuperview];
    }
    self.webView = nil;
}

#pragma mark WKWebViewDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    NSString *url = webView.URL.absoluteString;
        
    if([url localizedCaseInsensitiveContainsString:@"http://www.tcstzg.com"]){
        
        [webView stopLoading];
        return;
    }

}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
//    NSLog(@"--->>");
    //获取页面标题
    NSString* getTitleJS = @"document.title";
    MY_WEAK;
    [webView evaluateJavaScript:getTitleJS completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        weakSelf.title = result;
    }];
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    
}

- (void)webView:(WKWebView *)webView didFailLoadWithError:(NSError *)error
{
    
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    
}

- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
    
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
//    if (navigationAction.targetFrame == nil) {
//        [webView loadRequest:navigationAction.request];
//    }
//
//    if ([webView.URL.absoluteString hasPrefix:@"https://itunes.apple.com"] || [webView.URL.absoluteString hasPrefix:@"https://apps.apple.com"])
//    {
//        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
//        decisionHandler(WKNavigationActionPolicyCancel);
//    }
//    else
//    {
//        decisionHandler(WKNavigationActionPolicyAllow);
//    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
//    NSLog(@"createWebViewWithConfiguration");
//    if (!navigationAction.targetFrame.isMainFrame) {
//        [webView loadRequest:navigationAction.request];
//    }
    return nil;
}

//页面加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
{
    [self.myProgressView setProgress:0 animated:NO];
}

@end
